<template>
  <div class="knowledge-graph-dashboard">
    <!-- 查询区域 -->
    <div class="search-section">
      <div class="search-form">
        <el-input
            clearable
            v-model="search.name"
            placeholder="请输入姓名" style="flex: 1; margin-right: 10px;"
        />
        <el-input
            clearable
            v-model="search.phone"
            placeholder="请输入手机号" style="flex: 1; margin-right: 10px;"
        />
        <el-input
            clearable
            v-model="search.idCard"
            placeholder="请输入身份证号" style="flex: 1; margin-right: 10px;"
        />
        <el-button type="primary" @click="quickSearch">智能分析</el-button>
        <el-button type="danger" @click="initDefaultGraph">系统图谱</el-button>
        <el-button type="warning" @click="initKnowledgeGraph">案件图谱</el-button>
      </div>
    </div>

    <div class="content-wrapper">
      <!-- 左侧：知识图谱容器（斥候系统图谱 / 案件图谱 动态切换） -->
      <div class="graph-section">
        <div class="graph-container">
          <div ref="graphContainer" class="graph-content"></div>
        </div>
      </div>

      <!-- 右侧：统计信息 -->
<!--      <div class="stats-section">-->
<!--        <div class="stat-card">-->
<!--          <div class="stat-value">{{ stats.totalCases }}</div>-->
<!--          <div class="stat-label">案件总数</div>-->
<!--        </div>-->
<!--        <div class="stat-card">-->
<!--          <div class="stat-value">{{ stats.caseTypes }}</div>-->
<!--          <div class="stat-label">案件类型</div>-->
<!--        </div>-->
<!--&lt;!&ndash;        <div class="stat-card">&ndash;&gt;-->
<!--&lt;!&ndash;          <div class="stat-value">{{ stats.locatableCases }}</div>&ndash;&gt;-->
<!--&lt;!&ndash;          <div class="stat-label">可拘传案件</div>&ndash;&gt;-->
<!--&lt;!&ndash;        </div>&ndash;&gt;-->
<!--&lt;!&ndash;        <div class="stat-card">&ndash;&gt;-->
<!--&lt;!&ndash;          <div class="stat-value">{{ stats.relatedCases }}</div>&ndash;&gt;-->
<!--&lt;!&ndash;          <div class="stat-label">可确定关联人案件</div>&ndash;&gt;-->
<!--&lt;!&ndash;        </div>&ndash;&gt;-->
<!--        &lt;!&ndash; 新增不动产统计卡片 &ndash;&gt;-->
<!--        <div class="stat-card">-->
<!--          <div class="stat-value">164</div>-->
<!--          <div class="stat-label">不动产数据(101人)</div>-->
<!--        </div>-->
<!--        <div class="stat-card">-->
<!--          <div class="stat-value">205</div>-->
<!--          <div class="stat-label">个企数据(81人)</div>-->
<!--        </div>-->
<!--      </div>-->
    </div>
  </div>
</template>

<script>
import {ref, onMounted, onBeforeUnmount, nextTick, getCurrentInstance} from 'vue';
import * as echarts from 'echarts';
import {useRouter} from 'vue-router';
import MessageBoxContent from './MessageBoxContent.vue';
import axios from 'axios';
import {ElMessageBox} from "element-plus";

export default {
  name: 'KnowledgeGraphDashboard',
  setup() {
    const router = useRouter();
    const graphContainer = ref(null);
    let graphChart = null;

    const search = ref({
      name: '',
      phone: '',
      idCard: ''
    });

    const stats = ref({
      totalCases: 0,
      caseTypes: 0,
      locatableCases: 0,
      relatedCases: 0
    });

    const caseTypes = ref([]);

    // ========================
    // 加载案件类型（预加载，不初始化图谱）
    // ========================
    const loadCaseTypes = () => {
      axios.get("/api/caseInformation/getCaseTypeStats")
          .then(response => {
            caseTypes.value = Object.keys(response.data)
                .map(type => ({
                  name: type,
                  count: response.data[type]
                }))
                .sort((a, b) => b.count - a.count);
          })
          .catch(() => {
            caseTypes.value = [
              {name: '民间借贷纠纷', count: 320},
              {name: '买卖合同纠纷', count: 280},
              {name: '金融借款合同纠纷', count: 195},
              {name: '离婚纠纷', count: 160},
              {name: '机动车交通事故责任纠纷', count: 120},
              {name: '劳动争议', count: 95},
              {name: '建设工程施工合同纠纷', count: 80},
              {name: '其他', count: 298}
            ];
          });
    };

    // ========================
    // 初始化默认图谱：斥候系统
    // ========================
    // ========================
// 初始化默认图谱：斥候系统（扩展版）
// ========================
    // ========================
// 初始化默认图谱：斥候系统（优化版，避免交叉连接）
// ========================
    const initDefaultGraph = () => {
      if (!graphContainer.value) {
        console.error('graphContainer is null or undefined');
        return;
      }

      if (graphChart) {
        graphChart.dispose();
      }

      graphChart = echarts.init(graphContainer.value);

      const nodes = [
        {
          id: 'system',
          name: '海法 · 斥候',
          symbolSize: 150,
          category: 0,
          draggable: true,
          label: {
            fontSize: 25 // 设置字体大小为20
          },
          itemStyle: {color: '#409eff'},
          x: 500,
          y: 300,
          fixed: true
        },
        {
          id: 'songda',
          name: '司法送达/强制拘传',
          symbolSize: 135,
          category: 1,
          draggable: true,
          itemStyle: {color: '#67c23a'},
          x: 440,
          y: 260,
          fixed: true
        },
        {
          id: 'guanlian',
          name: '关联人/财产查询',
          symbolSize: 120,
          category: 1,
          draggable: true,
          itemStyle: {color: '#e6a23c'},
          x: 440,
          y: 340,
          fixed: true
        },
        {
          id: 'qingchang',
          name: '强制清场辅助',
          symbolSize: 120,
          category: 1,
          draggable: true,
          itemStyle: {color: '#f56c6c'},
          x: 560,
          y: 260,
          fixed: true
        },
        {
          id: 'pinggu',
          name: '企业评估/反担保',
          symbolSize: 120,
          category: 1,
          draggable: true,
          itemStyle: {color: '#909399'},
          x: 560,
          y: 340,
          fixed: true
        },
        // 数据来源节点，每个业务模块专属，位置更靠近业务模块
        {
          id: 'songda_meituan_data',
          name: '不动产数据',
          symbolSize: 80,
          category: 2,
          draggable: true,
          itemStyle: {color: '#a0cfff'}, // 浅蓝色，与业务模块颜色区分
          x: 380,
          y: 240,
          fixed: true
        },
        {
          id: 'songda_jd_data',
          name: '网购数据',
          symbolSize: 80,
          category: 2,
          draggable: true,
          itemStyle: {color: '#a0cfff'}, // 浅蓝色，与业务模块颜色区分
          x: 380,
          y: 280,
          fixed: true
        },
        {
          id: 'guanlian_meituan_data',
          name: '美团数据',
          symbolSize: 80,
          category: 2,
          draggable: true,
          itemStyle: {color: '#a0cfff'}, // 浅蓝色，与业务模块颜色区分
          x: 380,
          y: 320,
          fixed: true
        },
        {
          id: 'guanlian_jd_data',
          name: '网购数据',
          symbolSize: 80,
          category: 2,
          draggable: true,
          itemStyle: {color: '#a0cfff'}, // 浅蓝色，与业务模块颜色区分
          x: 380,
          y: 360,
          fixed: true
        },
        {
          id: 'qingchang_meituan_data',
          name: '美团数据',
          symbolSize: 80,
          category: 2,
          draggable: true,
          itemStyle: {color: '#a0cfff'}, // 浅蓝色，与业务模块颜色区分
          x: 620,
          y: 220,
          fixed: true
        },
        {
          id: 'qingchang_jd_data',
          name: '网购数据',
          symbolSize: 80,
          category: 2,
          draggable: true,
          itemStyle: {color: '#a0cfff'}, // 浅蓝色，与业务模块颜色区分
          x: 620,
          y: 260,
          fixed: true
        },
        {
          id: 'qingchang_real_estate_data',
          name: '不动产数据',
          symbolSize: 80,
          category: 2,
          draggable: true,
          itemStyle: {color: '#a0cfff'}, // 浅蓝色，与业务模块颜色区分
          x: 620,
          y: 300,
          fixed: true
        },
        {
          id: 'enterprise_data',
          name: '企业数据',
          symbolSize: 80,
          category: 2,
          draggable: true,
          itemStyle: {color: '#a0cfff'}, // 浅蓝色，与业务模块颜色区分
          x: 620,
          y: 380,
          fixed: true
        }
      ];

      const links = [
        {source: 'system', target: 'songda', name: '支撑'},
        {source: 'system', target: 'guanlian', name: '支撑'},
        {source: 'system', target: 'qingchang', name: '支撑'},
        {source: 'system', target: 'pinggu', name: '支撑'},
        // 数据来源连接（一对一，避免交叉）
        {source: 'songda', target: 'songda_meituan_data', name: '数据来源'},
        {source: 'songda', target: 'songda_jd_data', name: '数据来源'},
        {source: 'guanlian', target: 'guanlian_meituan_data', name: '数据来源'},
        {source: 'guanlian', target: 'guanlian_jd_data', name: '数据来源'},
        {source: 'qingchang', target: 'qingchang_meituan_data', name: '数据来源'},
        {source: 'qingchang', target: 'qingchang_jd_data', name: '数据来源'},
        {source: 'qingchang', target: 'qingchang_real_estate_data', name: '数据来源'},
        {source: 'pinggu', target: 'enterprise_data', name: '数据来源'}
      ];

      const option = {
        title: {
          // text: '海法 · 斥候',
          top: '20',
          left: '20',
          textStyle: {
            fontSize: 28,
            fontWeight: 'bold',
            color: '#1a73e8'
          }
        },
        tooltip: {
          formatter: function (params) {
            if (params.dataType === 'node') {
              return params.name;
            } else if (params.dataType === 'edge') {
              return `${params.data.source} → ${params.data.target}<br/>关系: ${params.data.name}`;
            }
            return '';
          }
        },
        legend: [{
          data: ['核心系统', '业务模块', '数据来源'],
          top: '20',
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 16
          }
        }],
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
          name: '斥候系统图谱',
          type: 'graph',
          layout: 'none', // 使用固定布局避免交叉
          data: nodes,
          links: links,
          categories: [
            {name: '核心系统', itemStyle: {color: '#409eff'}},
            {name: '业务模块', itemStyle: {color: '#67c23a'}},
            {name: '数据来源', itemStyle: {color: '#a0cfff'}} // 统一数据来源颜色
          ],
          roam: true,
          label: {
            show: true,
            position: 'inside',
            formatter: '{b}',
            fontSize: 16,
            color: '#000000'
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {width: 5}
          },
          lineStyle: {
            color: 'source',
            curveness: 0.1, // 稍微增加曲线避免直线过于生硬
            width: 2
          }
        }]
      };

      graphChart.setOption(option, true);

      graphChart.off('click');
      graphChart.on('click', (params) => {
        if (params.dataType === 'node') {
          const nodeId = params.data.id;
          switch (nodeId) {
            case 'songda':
              router.push('/manage2');
              break;
            case 'guanlian':
              router.push('/manage3');
              break;
            case 'qingchang':
              router.push('/manage4');
              break;
            case 'pinggu':
              router.push('/manage10');
              break;
            default:
              console.log('点击了未知节点:', nodeId);
          }
        }
      });
    };






    // ========================
    // 初始化案件类型分布图谱（中心辐射图）
    // ========================
    const initKnowledgeGraph = () => {
      if (!graphContainer.value) return;

      if (graphChart) {
        graphChart.dispose();
      }
      graphChart = echarts.init(graphContainer.value);

      const nodes = [
        {
          id: 'center',
          name: '案件类型分析',
          symbolSize: 100,
          category: 0,
          draggable: true,
          value: '中心节点'
        }
      ];

      caseTypes.value.forEach((type, index) => {
        nodes.push({
          id: `type_${index}`,
          name: type.name,
          symbolSize: 60,
          category: 1,
          draggable: true,
          value: `案件数量: ${type.count}`,
          caseType: type.name
        });
      });

      const links = caseTypes.value.map((type, index) => ({
        source: 'center',
        target: `type_${index}`,
        name: '包含'
      }));

      const option = {
        title: {
          text: '案件类型分布图谱',
          subtext: '点击案件类型查看详细信息',
          top: '20',
          left: '20',
          textStyle: {
            fontSize: 20,
            fontWeight: 'bold',
            color: '#1a73e8',
            textShadowColor: 'rgba(0, 0, 0, 0.2)',
            textShadowBlur: 2,
            textShadowOffsetX: 1,
            textShadowOffsetY: 1
          },
          subtextStyle: {
            color: '#444444',
            fontSize: 16,
            fontWeight: 'bold',
            fontStyle: 'normal',
            textShadowColor: 'rgba(0, 0, 0, 0.2)',
            textShadowBlur: 2,
            textShadowOffsetX: 1,
            textShadowOffsetY: 1
          }
        },
        tooltip: {
          formatter: function (params) {
            if (params.dataType === 'node') {
              return `${params.name}<br/>${params.data.value || ''}`;
            } else if (params.dataType === 'edge') {
              return `${params.data.source} -> ${params.data.target}<br/>${params.data.name || ''}`;
            }
            return '';
          }
        },
        legend: [{
          data: ['中心节点', '案件类型'],
          bottom: '10',
          right: '10',
          textStyle: {color: '#333'}
        }],
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
          name: '案件类型图谱',
          type: 'graph',
          layout: 'force',
          force: {
            repulsion: 550,
            gravity: 0.1,
            edgeLength: 200,
            layoutAnimation: true
          },
          data: nodes,
          links: links,
          categories: [
            {name: '中心节点', itemStyle: {color: '#409eff'}},
            {name: '案件类型', itemStyle: {color: '#67c23a'}}
          ],
          roam: true,
          label: {
            show: true,
            position: 'inside',
            formatter: '{b}',
            fontSize: 14,
            color: '#000000',
            overflow: 'truncate',
            width: 90
          },
          labelLayout: {
            hideOverlap: false
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {width: 5}
          },
          lineStyle: {
            color: 'source',
            curveness: 0.1
          }
        }]
      };

      graphChart.setOption(option, true);

      graphChart.off('click');
      graphChart.on('click', (params) => {
        if (params.dataType === 'node' && params.data.caseType && params.data.id !== 'center') {
          loadCaseDetailsByType(params.data.caseType);
        }
      });
    };

    // ========================
    // 根据案件类型加载案件详情图谱
    // ========================
    const loadCaseDetailsByType = (caseType) => {
      if (graphChart) {
        graphChart.dispose();
      }
      graphChart = echarts.init(graphContainer.value);

      axios.post("/api/caseInformation/getByCaseType", {
        caseType: caseType
      }).then(response => {
        const cases = response.data;
        if (cases && cases.length > 0) {
          const nodes = [];
          const links = [];

          const mainNode = {
            id: 'main',
            name: caseType,
            symbolSize: 100,
            category: 0,
            draggable: true,
            value: `案件数量: ${cases.length}`,
            caseType: caseType
          };
          nodes.push(mainNode);

          const displayCases = cases.slice(0, 10);
          displayCases.forEach((caseInfo, index) => {
            const nodeId = `case_${index}`;
            nodes.push({
              id: nodeId,
              name: caseInfo.anHao || `案件${index + 1}`,
              symbolSize: 60,
              category: 1,
              draggable: true,
              value: `被查询人: ${caseInfo.executor || '未知'}\n金额: ${caseInfo.caseMoney || '未知'}`,
              caseInfo: caseInfo
            });

            links.push({
              source: 'main',
              target: nodeId,
              name: '包含'
            });
          });

          const option = {
            title: {
              text: `${caseType}案件详情`,
              subtext: '点击案件节点查看详细信息，点击中心节点返回',
              top: '20',
              left: '20',
              textStyle: {
                fontSize: 20,
                fontWeight: 'bold',
                color: '#1a73e8',
                textShadowColor: 'rgba(0, 0, 0, 0.2)',
                textShadowBlur: 2,
                textShadowOffsetX: 1,
                textShadowOffsetY: 1
              },
              subtextStyle: {
                color: '#444444',
                fontSize: 16,
                fontWeight: 'bold',
                fontStyle: 'normal',
                textShadowColor: 'rgba(0, 0, 0, 0.2)',
                textShadowBlur: 2,
                textShadowOffsetX: 1,
                textShadowOffsetY: 1
              }
            },
            tooltip: {
              formatter: function (params) {
                if (params.dataType === 'node') {
                  return `${params.name}<br/>${params.data.value || ''}`;
                } else if (params.dataType === 'edge') {
                  return `${params.data.source} -> ${params.data.target}<br/>${params.data.name || ''}`;
                }
                return '';
              }
            },
            legend: [{
              data: ['案件类型', '具体案件'],
              bottom: '10',
              right: '10',
              textStyle: {color: '#333'}
            }],
            animationDuration: 1500,
            animationEasingUpdate: 'quinticInOut',
            series: [{
              name: '案件详情图谱',
              type: 'graph',
              layout: 'force',
              force: {
                repulsion: 550,
                gravity: 0.1,
                edgeLength: 200,
                layoutAnimation: true
              },
              data: nodes,
              links: links,
              categories: [
                {name: '案件类型', itemStyle: {color: '#409eff'}},
                {name: '具体案件', itemStyle: {color: '#67c23a'}}
              ],
              roam: true,
              label: {
                show: true,
                position: 'inside',
                formatter: '{b}',
                fontSize: 14,
                color: '#000000',
                overflow: 'truncate',
                width: 90
              },
              labelLayout: {
                hideOverlap: false
              },
              emphasis: {
                focus: 'adjacency',
                lineStyle: {width: 5}
              },
              lineStyle: {
                color: 'source',
                curveness: 0.1
              }
            }]
          };

          graphChart.setOption(option, true);

          graphChart.off('click');
          // graphChart.on('click', (newParams) => {
          //   if (newParams.dataType === 'node' && newParams.data.caseInfo) {
          //     const caseInfo = newParams.data.caseInfo;
          //     router.push({
          //       name: 'DataSummary',
          //       query: {
          //         idNumber: caseInfo.idNumber,
          //         name: caseInfo.executor,
          //         phone: caseInfo.phone
          //       }
          //     });
          //   } else if (newParams.dataType === 'node' && newParams.data.caseType) {
          //     initKnowledgeGraph();
          //   }
          // });
          // 在 loadCaseDetailsByType 函数中，找到 graphChart.on('click', ...) 部分，替换为以下代码：

          graphChart.on('click', (newParams) => {
            if (newParams.dataType === 'node' && newParams.data.caseInfo) {
              const caseInfo = newParams.data.caseInfo;

              // 创建 VNode
              const { h } = require('vue');
              const vnode = h(MessageBoxContent, { caseInfo: caseInfo });

              ElMessageBox({
                title: '页面跳转选择',
                message: vnode,
                showCancelButton: true,
                confirmButtonText: '鱼骨图分析',
                cancelButtonText: '数据汇总',
                confirmButtonClass: 'el-button--success',
                cancelButtonClass: 'el-button--primary',
                type: 'info',
                center: true,
                roundButton: true,
                customStyle: {
                  width: '420px'
                }
              }).then(() => {
                // 跳转到鱼骨图分析页面
                router.push({
                  name: 'YuGu',
                  query: {
                    idNumber: caseInfo.idNumber,
                    name: caseInfo.executor,
                    phone: caseInfo.phone
                  }
                });
              }).catch((action) => {
                // 只有点击取消按钮时才跳转到数据汇总页面
                if (action === 'cancel') {
                  router.push({
                    name: 'DataSummary',
                    query: {
                      idNumber: caseInfo.idNumber,
                      name: caseInfo.executor,
                      phone: caseInfo.phone
                    }
                  });
                }
                // // 如果是点击关闭按钮(X)则不执行任何跳转操作
              });
            } else if (newParams.dataType === 'node' && newParams.data.caseType) {
              initKnowledgeGraph();
            }
          });
        }
      });
    };

    // ========================
    // 根据搜索条件加载人员相关案件图谱
    // ========================
    const loadPersonRelatedCases = (searchData) => {
      if (graphChart) {
        graphChart.dispose();
      }
      graphChart = echarts.init(graphContainer.value);

      const requestData = {
        executor: searchData.name || "",
        phone: searchData.phone || "",
        idNumber: searchData.idCard || ""
      };

      axios.post("/api/caseInformation/getCaseInformation", requestData)
          .then(response => {
            const cases = response.data;
            if (cases && cases.length > 0) {
              const casesByType = {};
              cases.forEach(caseItem => {
                const type = caseItem.caseDetail || '其他';
                if (!casesByType[type]) {
                  casesByType[type] = [];
                }
                casesByType[type].push(caseItem);
              });

              const nodes = [];
              const links = [];

              let personName = searchData.name || '搜索结果';
              if (searchData.phone) personName += ` (${searchData.phone})`;
              if (searchData.idCard) personName += ` (${searchData.idCard})`;

              const mainNode = {
                id: 'person',
                name: personName,
                symbolSize: 80,
                category: 0,
                draggable: true,
                value: `相关案件: ${cases.length} 个`
              };
              nodes.push(mainNode);

              Object.keys(casesByType).forEach((caseType, index) => {
                const typeNodeId = `type_${index}`;
                nodes.push({
                  id: typeNodeId,
                  name: caseType,
                  symbolSize: 60,
                  category: 1,
                  draggable: true,
                  value: `案件数量: ${casesByType[caseType].length}`,
                  caseType: caseType
                });

                links.push({
                  source: 'person',
                  target: typeNodeId,
                  name: '涉及'
                });
              });

              const option = {
                title: {
                  text: `人员"${personName}"相关案件`,
                  subtext: '点击案件类型查看详细信息，点击中心节点返回',
                  top: '20',
                  left: '20',
                  textStyle: {
                    fontSize: 20,
                    fontWeight: 'bold',
                    color: '#1a73e8',
                    textShadowColor: 'rgba(0, 0, 0, 0.2)',
                    textShadowBlur: 2,
                    textShadowOffsetX: 1,
                    textShadowOffsetY: 1
                  },
                  subtextStyle: {
                    color: '#444444',
                    fontSize: 16,
                    fontWeight: 'bold',
                    fontStyle: 'normal',
                    textShadowColor: 'rgba(0, 0, 0, 0.2)',
                    textShadowBlur: 2,
                    textShadowOffsetX: 1,
                    textShadowOffsetY: 1
                  }
                },
                tooltip: {
                  formatter: function (params) {
                    if (params.dataType === 'node') {
                      return `${params.name}<br/>${params.data.value || ''}`;
                    } else if (params.dataType === 'edge') {
                      return `${params.data.source} -> ${params.data.target}<br/>${params.data.name || ''}`;
                    }
                    return '';
                  }
                },
                legend: [{
                  data: ['人员', '案件类型'],
                  bottom: '10',
                  right: '10',
                  textStyle: {color: '#333'}
                }],
                animationDuration: 1500,
                animationEasingUpdate: 'quinticInOut',
                series: [{
                  name: '人员相关案件图谱',
                  type: 'graph',
                  layout: 'force',
                  force: {
                    repulsion: 300,
                    gravity: 0.1,
                    edgeLength: 200,
                    layoutAnimation: true
                  },
                  data: nodes,
                  links: links,
                  categories: [
                    {name: '人员', itemStyle: {color: '#409eff'}},
                    {name: '案件类型', itemStyle: {color: '#67c23a'}}
                  ],
                  roam: true,
                  label: {
                    show: true,
                    position: 'inside',
                    formatter: '{b}',
                    fontSize: 12,
                    color: '#000000'
                  },
                  emphasis: {
                    focus: 'adjacency',
                    lineStyle: {width: 5}
                  },
                  lineStyle: {
                    color: 'source',
                    curveness: 0.1
                  }
                }]
              };

              graphChart.setOption(option, true);

              graphChart.off('click');
              graphChart.on('click', (params) => {
                if (params.dataType === 'node' && params.data.caseType) {
                  showCasesOfType(params.data.caseType, casesByType[params.data.caseType]);
                } else if (params.dataType === 'node' && params.data.id === 'person') {
                  initKnowledgeGraph();
                }
              });
            } else {
              const option = {
                title: {
                  text: '未找到相关案件',
                  subtext: '请尝试其他搜索条件',
                  top: 'center',
                  left: 'center',
                  textStyle: {
                    fontSize: 20,
                    fontWeight: 'bold',
                    color: '#1a73e8',
                    textShadowColor: 'rgba(0, 0, 0, 0.2)',
                    textShadowBlur: 2,
                    textShadowOffsetX: 1,
                    textShadowOffsetY: 1
                  },
                }
              };
              graphChart.setOption(option, true);
            }
          })
          .catch(() => {
            const option = {
              title: {
                text: '搜索失败',
                subtext: '请稍后重试',
                top: 'center',
                left: 'center',
                textStyle: {
                  fontSize: 20,
                  fontWeight: 'bold',
                  color: '#1a73e8',
                  textShadowColor: 'rgba(0, 0, 0, 0.2)',
                  textShadowBlur: 2,
                  textShadowOffsetX: 1,
                  textShadowOffsetY: 1
                },
              }
            };
            graphChart.setOption(option, true);
          });
    };

    // ========================
    // 显示特定类型下的案件图谱
    // ========================
    const showCasesOfType = (caseType, cases) => {
      if (graphChart) {
        graphChart.dispose();
      }
      graphChart = echarts.init(graphContainer.value);

      const nodes = [];
      const links = [];

      const mainNode = {
        id: 'main',
        name: caseType,
        symbolSize: 80,
        category: 0,
        draggable: true,
        value: `案件数量: ${cases.length}`,
        caseType: caseType
      };
      nodes.push(mainNode);

      cases.forEach((caseInfo, index) => {
        const nodeId = `case_${index}`;
        nodes.push({
          id: nodeId,
          name: caseInfo.anHao || `案件${index + 1}`,
          symbolSize: 60,
          category: 1,
          draggable: true,
          value: `被查询人: ${caseInfo.executor || '未知'}\n金额: ${caseInfo.caseMoney || '未知'}`,
          caseInfo: caseInfo
        });

        links.push({
          source: 'main',
          target: nodeId,
          name: '包含'
        });
      });

      const option = {
        title: {
          text: `${caseType}案件详情`,
          subtext: '点击案件节点查看详细信息，点击中心节点返回',
          top: '20',
          left: '20',
          textStyle: {
            fontSize: 20,
            fontWeight: 'bold',
            color: '#1a73e8',
            textShadowColor: 'rgba(0, 0, 0, 0.2)',
            textShadowBlur: 2,
            textShadowOffsetX: 1,
            textShadowOffsetY: 1
          },
          subtextStyle: {
            color: '#444444',
            fontSize: 16,
            fontWeight: 'bold',
            fontStyle: 'normal',
            textShadowColor: 'rgba(0, 0, 0, 0.2)',
            textShadowBlur: 2,
            textShadowOffsetX: 1,
            textShadowOffsetY: 1
          }
        },
        tooltip: {
          formatter: function (params) {
            if (params.dataType === 'node') {
              return `${params.name}<br/>${params.data.value || ''}`;
            } else if (params.dataType === 'edge') {
              return `${params.data.source} -> ${params.data.target}<br/>${params.data.name || ''}`;
            }
            return '';
          }
        },
        legend: [{
          data: ['案件类型', '具体案件'],
          bottom: '10',
          right: '10',
          textStyle: {color: '#333'}
        }],
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
          name: '案件详情图谱',
          type: 'graph',
          layout: 'force',
          force: {
            repulsion: 300,
            gravity: 0.1,
            edgeLength: 200,
            layoutAnimation: true
          },
          data: nodes,
          links: links,
          categories: [
            {name: '案件类型', itemStyle: {color: '#409eff'}},
            {name: '具体案件', itemStyle: {color: '#67c23a'}}
          ],
          roam: true,
          label: {
            show: true,
            position: 'inside',
            formatter: '{b}',
            fontSize: 12,
            color: '#000000'
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {width: 5}
          },
          lineStyle: {
            color: 'source',
            curveness: 0.1
          }
        }]
      };

      graphChart.setOption(option, true);

      graphChart.off('click');
      // graphChart.on('click', (params) => {
      //   if (params.dataType === 'node' && params.data.caseInfo) {
      //     const caseInfo = params.data.caseInfo;
      //     router.push({
      //       name: 'DataSummary',
      //       query: {
      //         idNumber: caseInfo.idNumber,
      //         name: caseInfo.executor,
      //         phone: caseInfo.phone
      //       }
      //     });
      //   } else if (params.dataType === 'node' && params.data.caseType) {
      //     initKnowledgeGraph();
      //   }
      // });
      // 修改 KG.vue 中的图谱点击事件处理函数
      // 修改图谱点击事件处理函数
      graphChart.on('click', (params) => {
        if (params.dataType === 'node' && params.data.caseInfo) {
          const caseInfo = params.data.caseInfo;

          // 创建 VNode
          const { h, resolveComponent } = require('vue');
          const vnode = h(MessageBoxContent, { caseInfo: caseInfo });

          ElMessageBox({
            title: '页面跳转选择',
            message: vnode,
            showCancelButton: true,
            confirmButtonText: '鱼骨图分析',
            cancelButtonText: '数据汇总',
            confirmButtonClass: 'el-button--success',
            cancelButtonClass: 'el-button--primary',
            type: 'info',
            center: true,
            roundButton: true,
            customStyle: {
              width: '420px'
            }
          }).then(() => {
            // 跳转到鱼骨图分析页面
            router.push({
              name: 'YuGu',
              query: {
                idNumber: caseInfo.idNumber,
                name: caseInfo.executor,
                phone: caseInfo.phone
              }
            });

            // 通知父组件收缩侧边栏
            const instance = getCurrentInstance();
            if (instance && instance.emit) {
              instance.emit('collapse-sidebar');
            }
          }).catch((action) => {
            // 只有点击取消按钮时才跳转到数据汇总页面
            if (action === 'cancel') {
              router.push({
                name: 'DataSummary',
                query: {
                  idNumber: caseInfo.idNumber,
                  name: caseInfo.executor,
                  phone: caseInfo.phone
                }
              });
            }
            // 如果是点击关闭按钮(X)则不执行任何跳转操作
          });
        } else if (params.dataType === 'node' && params.data.caseType) {
          initKnowledgeGraph();
        }
      });

    };

    // ========================
    // 加载统计面板数据
    // ========================
    const loadStats = () => {
      axios.get("/api/caseInformation/count")
          .then(response => stats.value.totalCases = response.data)
          .catch(() => stats.value.totalCases = 1248);

      axios.get("/api/caseInformation/getCountTypes")
          .then(response => stats.value.caseTypes = response.data)
          .catch(() => stats.value.caseTypes = 8);

      axios.get("/api/caseInformation/locatableCount")
          .then(response => stats.value.locatableCases = response.data)
          .catch(() => stats.value.locatableCases = 5);

      axios.get("/api/relatedPeople/caseCount")
          .then(response => stats.value.relatedCases = response.data)
          .catch(() => stats.value.relatedCases = 5);
    };

    // ========================
    // 快速搜索入口
    // ========================
    const quickSearch = () => {
      const searchData = {
        name: search.value.name.trim(),
        phone: search.value.phone.trim(),
        idCard: search.value.idCard.trim()
      };

      if (searchData.name || searchData.phone || searchData.idCard) {
        loadPersonRelatedCases(searchData);
      } else {
        initDefaultGraph();
      }
    };

    // ========================
    // 窗口大小自适应
    // ========================
    const handleResize = () => {
      if (graphChart) {
        graphChart.resize();
      }
    };

    // ========================
    // 生命周期
    // ========================
    onMounted(() => {
      loadStats();
      loadCaseTypes(); // 预加载数据，不初始化图谱
      window.addEventListener('resize', handleResize);
      nextTick(() => {
        initDefaultGraph(); // 默认显示斥候图谱
      });
    });

    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize);
      if (graphChart) {
        graphChart.dispose();
      }
    });

    return {
      graphContainer,
      search,
      stats,
      quickSearch,
      initDefaultGraph, // 暴露给“返回系统图谱”按钮
      initKnowledgeGraph
    };
  }
};
</script>

<style scoped>
.knowledge-graph-dashboard {
  padding: 20px;
  /* 核心修改：占满整个视口高度 */
  height: 100vh;
  /* 核心修改：隐藏内部滚动条，滚动由浏览器控制 */
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
}

.search-section {
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  /* 搜索区域不参与 flex 布局的高度计算，因此需要明确其高度或让其自然撑开 */
}

.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 核心修改：内容区域使用 calc 精确计算剩余高度 */
.content-wrapper {
  display: flex;
  gap: 15px;
  /* 核心修改：减去搜索区域的高度(62px padding + 20px margin)和自身的padding(20px*2) */
  /* 实际计算可能需要微调，这里是一个估算值 */
  height: calc(100vh - 62px - 20px - 20px - 20px);
  /* 确保子元素可以正确填充高度 */
  min-height: 0;
}

.graph-section {
  flex: 7;
  min-width: 0;
  /* 确保图谱容器填满其分配的空间 */
  height: 100%;
}

.stats-section {
  flex: 3;
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-width: 180px;
  /* 让统计卡片区域填满其分配的空间 */
  height: 100%;
}

/* 核心修改：确保图谱容器和内容区填满可用空间 */
.graph-container {
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding: 10px;
}

.graph-content {
  width: 100%;
  height: 100%;
}

.stat-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 5px;
  padding: 8px 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  backdrop-filter: blur(10px);
  /* flex: 1 使得每个卡片平分可用垂直空间 */
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 50px;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 2px;
}

.stat-label {
  font-size: 10px;
  color: #606266;
}

/* 移动端适配保持不变，但请注意在小屏幕上可能无法完全避免滚动 */
@media (max-width: 768px) {
  .knowledge-graph-dashboard {
    height: auto;
    padding: 10px;
    overflow: auto; /* 小屏幕允许滚动 */
  }

  .content-wrapper {
    flex-direction: column;
    height: auto;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-input,
  .search-form .el-button {
    width: 100%;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }

  .stats-section {
    flex-direction: row;
    flex-wrap: wrap;
    max-width: 100%;
    margin-top: 15px;
    height: auto; /* 移动端自动高度 */
  }

  .stat-card {
    min-width: 45%;
    flex: 0 0 auto; /* 移动端卡片不拉伸 */
  }
}
</style>



